﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;

namespace TK.Mqtt.Client
{
    /// <summary>
    /// MqttServiceCollectionExtensions
    /// </summary>
    public static class MqttServiceCollectionExtensions
    {
        /// <summary>
        /// 增加MQTT客户端服务
        /// </summary>
        public static MqttBuilder AddMqttClientWrapper(this IServiceCollection services, Action<MqttConfig> action)
        {
            if (action != null)
            {
                services.Configure<MqttConfig>(action);
            }

            AddMqttClient(services);
            return new MqttBuilder { ServiceCollection = services };
        }

        /// <summary>
        /// 增加MQTT客户端服务
        /// </summary>
        public static MqttBuilder AddMqttClientWrapper(this IServiceCollection services, IConfiguration configuration)
        {
            if (configuration != null)
            {
                services.Configure<MqttConfig>(configuration);
            }

            AddMqttClient(services);
            return new MqttBuilder { ServiceCollection = services };
        }

        /// <summary>
        /// 增加数据处理程序
        /// </summary>
        /// <typeparam name="THandler">IDataHandler</typeparam>
        /// <param name="services">IServiceCollection</param>
        public static IServiceCollection AddMqttDataHandler<THandler>(this IServiceCollection services) where THandler : class, IDataHandler
        {
            services.TryAddSingleton<IDataHandler, THandler>();
            return services;
        }

        /// <summary>
        /// 增加数据处理程序
        /// </summary>
        /// <typeparam name="THandler">IDataHandler</typeparam>
        /// <param name="builder">MqttBuilder</param>
        public static void AddMqttDataHandler<THandler>(this MqttBuilder builder) where THandler : class, IDataHandler
        {
            builder.ServiceCollection.TryAddSingleton<IDataHandler, THandler>();
        }

        /// <summary>
        /// 统一增加服务
        /// </summary>
        private static void AddMqttClient(IServiceCollection services)
        {
            services.TryAddSingleton<IMultiMqttClientWrapper, MultiMqttClientWrapper>();
            services.AddHostedService<MqttHostedService>();
        }
    }
}
